package com.cskaoyan.service.front;

import com.cskaoyan.bean.bo.front.cartbo.CartAddBO;
import com.cskaoyan.bean.bo.front.cartbo.CartCheckedBO;
import com.cskaoyan.bean.bo.front.cartbo.CartCheckoutBO;
import com.cskaoyan.bean.bo.front.cartbo.CartUpdateBO;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.front.cartvo.CartCheckoutAddressVO;
import com.cskaoyan.bean.vo.front.cartvo.CartCheckoutVO;
import com.cskaoyan.bean.vo.front.cartvo.CartIndexTotalVO;
import com.cskaoyan.bean.vo.front.cartvo.CartIndexVO;
import com.cskaoyan.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 12-江涛
 * @since 2022/10/13  23:37
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;


    @Override
    public CartIndexVO cartIndex() {

        //判断用户登录状态
        MarketUser marketUser = userInformation();
        if (marketUser == null) {
            return null;
        }

        //查询购物车商品表（cart）
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(marketUser.getId()); //当前用户Id
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        //用于计算购物车中 所有 商品数量
        int goodsCount = 0;
        //用于计算购物车中 所有 商品价格
        BigDecimal goodsAmount = new BigDecimal("0");
        //用于计算购物车中 选中 商品数量
        int checkedGoodsCount = 0;
        //用于计算购物车中 选中 商品价格
        BigDecimal checkedGoodsAmount = new BigDecimal("0");

        for (MarketCart marketCart : marketCarts) {

            goodsCount += marketCart.getNumber();
            goodsAmount = countAndAmount(marketCart, goodsAmount);
            if (marketCart.getChecked()) {

                checkedGoodsCount += marketCart.getNumber();
                checkedGoodsAmount = countAndAmount(marketCart, checkedGoodsAmount);
            }
        }

        //需要返回的VO
        CartIndexVO cartIndexVO = new CartIndexVO();
        CartIndexTotalVO cartIndexTotalVO = new CartIndexTotalVO();

        cartIndexVO.setCartList(marketCarts);

        cartIndexTotalVO.setCheckedGoodsAmount(checkedGoodsAmount);
        cartIndexTotalVO.setCheckedGoodsCount(checkedGoodsCount);
        cartIndexTotalVO.setGoodsAmount(goodsAmount);
        cartIndexTotalVO.setGoodsCount(goodsCount);
        cartIndexVO.setCartTotal(cartIndexTotalVO);

        return cartIndexVO;
    }


    @Override
    public CartIndexVO cartChecked(CartCheckedBO cartCheckedBO) {

        //判断用户登录状态
        MarketUser marketUser = userInformation();
        if (marketUser == null) {
            return null;
        }

        //根据productIds 修改商品 勾选状态
        Integer[] productIds = cartCheckedBO.getProductIds();

        int count = 0;
        for (Integer productId : productIds) {
            //根据userId 和 productId 修改 勾选状态 （约定：相同productId的商品加入购物车，只修改cart表中number值，不会新增一条数据；add方法中）
            count += marketCartMapper.updateByproductIdAndUserId(cartCheckedBO.getIsChecked(), productId, marketUser.getId());
        }

        if (count == cartCheckedBO.getProductIds().length) {

            return cartIndex();
        }

        return null;
    }

//    //正常情况，不会执行到此处 ; 将CartIndexTotalVO 中checkedGoodsCount 属性标记为10000 ，表示加入购物车失败
//    CartIndexVO cartIndexVO = new CartIndexVO();
//    CartIndexTotalVO cartIndexTotalVO = new CartIndexTotalVO();
//        cartIndexTotalVO.setCheckedGoodsCount(10000);
//        cartIndexVO.setCartTotal(cartIndexTotalVO);


    @Override
    public int cartAdd(CartAddBO cartAddBO) {

        //判断用户登录状态
        MarketUser marketUser = userInformation();
        if (marketUser == null) {
            return 0;
        }

        //判断购物车中是否存在相同 productId  （有，number相加；无，创建）
        // （约定：相同productId的商品加入购物车，只修改cart表中number值，不会新增一条数据）
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andProductIdEqualTo(cartAddBO.getProductId());
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);

        short number = cartAddBO.getNumber();
        if (marketCartList.size() != 0) {

            //删除原数据
            marketCartMapper.deleteByExample(marketCartExample);
            number = (short) (marketCartList.get(0).getNumber() + cartAddBO.getNumber());
        }

        //用于向cart表中添加数据
        MarketCart marketCart = new MarketCart();

        marketCart.setUserId(marketUser.getId());
        marketCart.setGoodsId(cartAddBO.getGoodsId());
        marketCart.setProductId(cartAddBO.getProductId());
        marketCart.setNumber(number);
        marketCart.setChecked(true);
        marketCart.setDeleted(false);

        //查询product表 得specifications
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(cartAddBO.getProductId());
        marketCart.setSpecifications(marketGoodsProduct.getSpecifications());

        //查询goods表
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(cartAddBO.getGoodsId());

        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());
        marketCart.setPrice(marketGoods.getRetailPrice());//这里赋值的是零售价格
        marketCart.setPicUrl(marketGoods.getPicUrl());
        marketCart.setAddTime(marketGoods.getAddTime());
        marketCart.setUpdateTime(marketGoods.getUpdateTime());

        //将数据存入cart 表
        int count = marketCartMapper.insertSelective(marketCart);

        if (count == 1) {

            //调用goodscount方法，显示购物车商品数量啊（小气泡）
            return (int) goodscount();
        }

        //加入购物车失败
        return 10000;
    }


    @Override
    public int fastadd(CartAddBO cartAddBO) {

        //将商品加入表中
        //登录状态在add方法中判断
        int state = cartAdd(cartAddBO);
        if (state == 0) {
            //未登录
            return 0;
        }
        if (state == 10000) {
            //加入购物车失败
            return 10000;
        }

        //state = 1 加入购物车成功，执行以下操作

        //获取刚刚加入购物车的cardId
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andProductIdEqualTo(cartAddBO.getProductId());

        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);

        //将购买商品数量放入Session 中，在下单（cartCheckout）方法中取出
        SecurityUtils.getSubject().getSession().setAttribute("number", cartAddBO.getNumber());
        List<Integer> cardIds = new ArrayList<>();
        cardIds.add(marketCartList.get(0).getId());
        SecurityUtils.getSubject().getSession().setAttribute("cardIds", cardIds);

        if (marketCartList != null) {

            return cartAddBO.getNumber();
        }
        //正常情况，不会执行到此处
        return 10000;
    }


    @Override
    public int cartUpdate(CartUpdateBO cartUpdateBO) {

        //查询goods_product表  查看库存是否充足
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(cartUpdateBO.getProductId());

        int count = 0;
        if (marketGoodsProduct.getNumber() >= cartUpdateBO.getNumber()) {
            //库存足够，修改cart 表中number
            count = marketCartMapper.updateNumberById(cartUpdateBO);
            if (count != 1) {
                //操作有误
                return -1;
            }
            return count;
        }
        //count = 0 ，库存不足
        return count;
    }


    @Override
    public CartCheckoutVO cartCheckout(CartCheckoutBO cartCheckoutBO) {

        //判断用户登录状态
        MarketUser marketUser = userInformation();
        if (marketUser == null) {
            return null;
        }

        //用于返回得VO
        CartCheckoutVO cartCheckoutVO = new CartCheckoutVO();

        cartCheckoutVO.setAddressId(cartCheckoutBO.getAddressId());
        cartCheckoutVO.setCartId(cartCheckoutBO.getCartId());
        cartCheckoutVO.setCouponId(cartCheckoutBO.getCouponId());
        cartCheckoutVO.setUserCouponId(cartCheckoutBO.getUserCouponId());
        cartCheckoutVO.setGrouponRulesId(cartCheckoutBO.getGrouponRulesId());

        cartCheckoutVO.setGrouponPrice(new BigDecimal("0"));//未使用优惠券情况，优惠金额为0
        cartCheckoutVO.setFreightPrice(new BigDecimal("10"));//运费为10
        cartCheckoutVO.setOrderTotalPrice(new BigDecimal("20"));


        //用于添加商品到 订单
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setFreightPrice(cartCheckoutVO.getFreightPrice());
        marketOrder.setIntegralPrice(new BigDecimal("0")); //用户积分减免
        marketOrder.setGrouponPrice(new BigDecimal("0")); // 团购优惠减免

        //查询address表 ,收货地址
        MarketAddress marketAddress;
        CartCheckoutAddressVO cartCheckoutAddressVO = new CartCheckoutAddressVO();

        try {

            if (cartCheckoutBO.getAddressId() != 0) {

                marketAddress = marketAddressMapper.selectByPrimaryKey(cartCheckoutBO.getAddressId());
                cartCheckoutAddressVO.setId(marketAddress.getId());
            } else {

                //默认地址
                MarketAddressExample marketAddressExample = new MarketAddressExample();
                marketAddressExample.createCriteria().andIsDefaultEqualTo(true);
                List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);

                marketAddress = marketAddresses.get(0);
            }
        } catch (Exception e) {

            //没有地址, 提示添加(将CheckedAddress 设置为null 作为标记)
            cartCheckoutVO.setCheckedAddress(null);
            return cartCheckoutVO;
        }

        cartCheckoutAddressVO.setName(marketAddress.getName());
        cartCheckoutAddressVO.setUserId(marketAddress.getUserId());
        cartCheckoutAddressVO.setProvince(marketAddress.getProvince());
        cartCheckoutAddressVO.setCity(marketAddress.getCity());
        cartCheckoutAddressVO.setCity(marketAddress.getCity());
        cartCheckoutAddressVO.setCounty(marketAddress.getCounty());
        cartCheckoutAddressVO.setAddressDetail(marketAddress.getAddressDetail());
        cartCheckoutAddressVO.setAreaCode(marketAddress.getAreaCode());
        cartCheckoutAddressVO.setTel(marketAddress.getTel());
        cartCheckoutAddressVO.setIsDefault(marketAddress.getIsDefault());
        cartCheckoutAddressVO.setAddTime(marketAddress.getAddTime());
        cartCheckoutAddressVO.setUpdateTime(marketAddress.getUpdateTime());
        cartCheckoutAddressVO.setDeleted(marketAddress.getDeleted());

        cartCheckoutVO.setCheckedAddress(cartCheckoutAddressVO);
        cartCheckoutVO.setAddressId(cartCheckoutBO.getAddressId());

        //添加订单 数据
        marketOrder.setMobile(marketAddress.getTel());
        marketOrder.setAddress(marketAddress.getAddressDetail());


        //查询cart表 ，获得cardId 以及商品信息
        List<MarketCart> marketCartList;
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();

        List<Integer> goodsIds = new ArrayList<>();
        List<Short> numbers = new ArrayList<>();
        List<String[]> specificationss = new ArrayList<>();
        if (cartCheckoutBO.getCartId() != 0) {

            // 立即下单进入
            //在Session 中获取fastadd 中cardId
            List<Integer> cardIds = (List<Integer>) SecurityUtils.getSubject().getSession().getAttribute("cardIds");
            criteria.andIdEqualTo(cardIds.get(0));
            marketCartList = marketCartMapper.selectByExample(marketCartExample);

            //在Session 中获取fastadd 中商品数量
            Short number = (Short) SecurityUtils.getSubject().getSession().getAttribute("number");
            marketCartList.get(0).setNumber(number);
            cartCheckoutVO.setCheckedGoodsList(marketCartList);

            // 添加订单 数据 （获取goodsId/ number/ specifications 放入Session）
            goodsIds.add(marketCartList.get(0).getGoodsId());
            SecurityUtils.getSubject().getSession().setAttribute("goodsIds", goodsIds);
            numbers.add(marketCartList.get(0).getNumber());
            SecurityUtils.getSubject().getSession().setAttribute("numbers", numbers);
            specificationss.add(marketCartList.get(0).getSpecifications());
            SecurityUtils.getSubject().getSession().setAttribute("specificationss", specificationss);
        } else {

            //购物车主页进入
            criteria.andCheckedEqualTo(true);
            criteria.andUserIdEqualTo(marketUser.getId());
            marketCartList = marketCartMapper.selectByExample(marketCartExample);
            cartCheckoutVO.setCheckedGoodsList(marketCartList);

            List<Integer> cardIds = new ArrayList<>();

            // 添加订单 数据  （获取goodsId/ number/ specifications 放入Session）
            for (MarketCart marketCart : marketCartList) {
                goodsIds.add(marketCart.getGoodsId());
                numbers.add(marketCart.getNumber());
                cardIds.add(marketCart.getId());
                specificationss.add(marketCart.getSpecifications());//此处修改
            }
            SecurityUtils.getSubject().getSession().setAttribute("goodsIds", goodsIds);
            SecurityUtils.getSubject().getSession().setAttribute("numbers", numbers);
            SecurityUtils.getSubject().getSession().setAttribute("specificationss", specificationss);
            SecurityUtils.getSubject().getSession().setAttribute("cardIds",cardIds);
        }

        //查询coupon 表，使用优惠券
        if (cartCheckoutBO.getCouponId() != 0 && cartCheckoutBO.getCouponId() != -1) {

            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(cartCheckoutBO.getCouponId());
            //优惠金额
            cartCheckoutVO.setCouponPrice(marketCoupon.getDiscount());

            //添加订单 数据
            marketOrder.setCouponPrice(marketCoupon.getDiscount());
        } else {
            BigDecimal bigDecimal = new BigDecimal("0");
            cartCheckoutVO.setCouponPrice(bigDecimal);
            //添加订单 数据
            marketOrder.setCouponPrice(bigDecimal);
        }

        //查询groupon 表，团购
        if (cartCheckoutBO.getGrouponRulesId() != 0) {

            // 团购优惠
            BigDecimal couponPrice = new BigDecimal("0");

            //添加订单 数据
            marketOrder.setGrouponPrice(couponPrice);
        }


        //查询coupon_user 表 ，获得可用优惠券数量  (availableCouponLength)
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria2 = marketCouponUserExample.createCriteria();
        criteria2.andUserIdEqualTo(marketUser.getId());
        criteria2.andDeletedEqualTo(false);

        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        cartCheckoutVO.setAvailableCouponLength(marketCouponUsers.size());

        //计算商品实际价格
        BigDecimal actualPrice1 = new BigDecimal("0");
        //1.获取总价
        for (MarketCart marketCart : marketCartList) {

            //该商品购买数量
            Short number = marketCart.getNumber();
            BigDecimal numberB = new BigDecimal(number);
            //该商品单价
            BigDecimal price = marketCart.getPrice();
            //该件商品总价
            BigDecimal priceCurrent = price.multiply(numberB);

            actualPrice1 = actualPrice1.add(priceCurrent);
        }

        //1.1 订单数据
        marketOrder.setGoodsPrice(actualPrice1);
        cartCheckoutVO.setGoodsTotalPrice(actualPrice1);

        //2.是否使用优惠券
        if (cartCheckoutBO.getCouponId() != 0 && cartCheckoutBO.getCouponId() != -1) {
            actualPrice1 = actualPrice1.subtract(cartCheckoutVO.getCouponPrice());
        }
        //3.最终实际价格 （扣除用户积分减免之后）
        cartCheckoutVO.setActualPrice(actualPrice1.subtract(marketOrder.getIntegralPrice()).add(marketOrder.getFreightPrice()));


        //添加订单 数据
        marketOrder.setUserId(marketUser.getId());

        //获取当前时间，作为order_sn
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(date);
        String str = format.replaceAll("[-,:, ]", "");
        marketOrder.setOrderSn(str);

        marketOrder.setOrderStatus((short) 201);//订单状态
        marketOrder.setAftersaleStatus((short) 0);//售后状态

        marketOrder.setConsignee(marketUser.getNickname());
        marketOrder.setMessage(null);
        marketOrder.setOrderPrice(marketOrder.getGoodsPrice().add(marketOrder.getFreightPrice()).subtract(marketOrder.getCouponPrice()));
        marketOrder.setActualPrice(cartCheckoutVO.getActualPrice());

        marketOrder.setPayId(str + "1"); //微信付款Id 采用订单编号（order_sn）加 1
        marketOrder.setPayTime(date);

        marketOrder.setAddTime(date);
        marketOrder.setUpdateTime(date);
        marketOrder.setDeleted(false);

        //放入Session 由submit方法添加订单
        SecurityUtils.getSubject().getSession().setAttribute("marketOrder", marketOrder);
////         添加order表 （先查询订单表是否有相同订单；有，更新  无，添加一条新数据）
//        marketOrderMapper.insertSelective(marketOrder);

        return cartCheckoutVO;
    }

    @Override
    public CartIndexVO cartDelete(Integer[] productIds) {

        //获取用户信息
        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        //修改card 表
        int count = 0;
        for (Integer productId : productIds) {
            count += marketCartMapper.updateByproductId(1, productId, marketUser.getId());
        }

        if (count == productIds.length) {
            return cartIndex();
        }
        //删除失败！
        return null;
    }

    @Override
    public long goodscount() {

        //判断用户登录状态 ，未登录，购物车商品数显示0（小气泡）
        MarketUser marketUser = userInformation();
        if (marketUser == null) {
            return -1;
        }

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andDeletedEqualTo(false);

        long count = marketCartMapper.countByExample(marketCartExample);
        return count;
    }


    /*
     * 抽取方法（cartIndex方法中）
     *
     * @return
     * @Author 12-江涛
     * @Date  2022/10/14 15:35
     */
    public BigDecimal countAndAmount(MarketCart marketCart, BigDecimal amount) {

        BigDecimal number = new BigDecimal(marketCart.getNumber());
        BigDecimal multiply = marketCart.getPrice().multiply(number);
        amount = amount.add(multiply);

        return amount;
    }

    /*
     * 判断用户登录状态
     *
     * @return
     * @Author 12-江涛
     * @Date  2022/10/16 12:17
     */
    public MarketUser userInformation() {

        MarketUser marketUser;
        try {
            marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        } catch (Exception e) {
            //返回null未登录状态  -->  BaseRespVo.couponError(10000,"请先登录商城");
            return null;
        }
        return marketUser;
    }

}
